package com.example.anew.journey.mynewjourney.logic.getVersion.persenter;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;

import com.example.anew.journey.mynewjourney.base.MyApplication;
import com.example.anew.journey.mynewjourney.config.RBConstants;
import com.example.anew.journey.mynewjourney.logic.getVersion.bean.GetVersionBean;
import com.example.anew.journey.mynewjourney.logic.getVersion.bean.PasswordFreeLoginBean;
import com.example.anew.journey.mynewjourney.logic.getVersion.model.GetVersionModel;
import com.example.anew.journey.mynewjourney.logic.getVersion.model.ISGetVersionModel;
import com.example.anew.journey.mynewjourney.logic.getVersion.view.ISGetVersionView;
import com.example.anew.journey.mynewjourney.logic.registeredOrLogin.RegisteredOrLoginActivity;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import cn.jesse.nativelogger.NLogger;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 杭州惟君医疗科技有限公司15
 * Created by 20433 on 2018/3/6
 */

public class GetVersionPersenter {
    private ISGetVersionView mISGetVersionView;
    private ISGetVersionModel mISGetVersionModel;
    private int p = RBConstants.COUNTDOWN;
    private Handler mHandler;
    private boolean flag = true;

    public GetVersionPersenter(ISGetVersionView iSGetVersionView) {
        this.mISGetVersionView = iSGetVersionView;
        mISGetVersionModel = new GetVersionModel();
    }

    /**
     * @desc 请求服务器获取验证码
     */
    public void requestNetworkGetVersionCode(Context mContext) {
       String tel =  mISGetVersionView.getPhoneNumber();
        if(flag) mISGetVersionView.changTimeOne();
        int state =  mISGetVersionView.getMyState();
       String my_state =  mISGetVersionView.getThirdPartyLoginState();
        NLogger.e("TAG","=====1====NetworkResponseDate============"+state);
        //NLogger.e("TAG","requestNetworkGetVersionCode==========="+state);
        if(state == 0 ){
            getRegisteredVersionCode(tel);
            return;
        }
        if(state == 1 ){
            NLogger.e("TAG","=======3==NetworkResponseDate============"+state);
            getPasswordFreeLoginVersionCode(tel,mContext);
            return;
        }
        if(my_state != null && my_state.equals("1")){
            getRegisteredVersionCode(tel);
        }
    }

    private void changTime() {

    }


    /**
     * @desc 点击下一步
     * */
    public void OnClickNext(Context mContext) {
        String trim = mISGetVersionView.getEtInputVersionCode();
        //NLogger.e("TAG","=====23====GetVersionPersenter===trim========="+trim);
        if (TextUtils.isEmpty(trim)) {
            mISGetVersionView.showToastInformation("请输入验证码");
            return;
        }
       int state =  mISGetVersionView.getMyState();
        //NLogger.e("TAG","=====23====GetVersionPersenter===state========="+state);
        if(state == 0 ){
            mISGetVersionView.toSetNameActivity(trim);
            return;
        }
        if(state == 1){
           String phoneNumber =  mISGetVersionView.getPhoneNumber();
            if(TextUtils.isEmpty(phoneNumber)) mISGetVersionView.toFinshBeforePager();
            submitRegisteredOrLogin(phoneNumber,trim,mContext);
            return;
        }
       String third_party_login_state =  mISGetVersionView.getThirdPartyLoginState();
        if(third_party_login_state != null && third_party_login_state.equals("1")) {
            mISGetVersionView.toSetNameActivity(trim);
            return;
        }

    }




    //获取免密码登陆验证码
    public void getPasswordFreeLoginVersionCode(String tel, final Context mContext) {

        String url = RBConstants.SERVER_URL+RBConstants.OTHER_GET_VERSION_CODE;
        NLogger.e("TAG","=====获取免密码登陆验证码====NetworkResponseDate============"+url);
        OkHttpUtils
                .get()
                .url(url)
                .addParams("tel", tel)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String NetworkResponseDate = response.body().string();
                        Gson gson =   new Gson();
                        //NLogger.e("TAG","=====获取免密码登陆验证码====NetworkResponseDate============"+NetworkResponseDate);
                        final GetVersionBean getVersion =  gson.fromJson(NetworkResponseDate,GetVersionBean.class);
                        // TODO 移植
                        MyApplication.getmHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                if(getVersion.errorCode == 200) {
                                    mISGetVersionView.showToastInformation("验证码发送成功");
                                }else{
                                    Intent intent = new Intent(mContext, RegisteredOrLoginActivity.class);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
                                    mContext.startActivity(intent);
                                   // mISGetVersionView.findshpager();
                                    mISGetVersionView.showToastInformation("验证码发送失败");
                                }

                            }
                        });


                        return null;
                    }
                    @Override
                    public void onError(Call call, Exception e, int id) {



                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });

    }

    //获取注册的验证码
    private void getRegisteredVersionCode(String tel) {
        String url = RBConstants.SERVER_URL+RBConstants.REGISTERED_GET_VERSION_CODE;
        OkHttpUtils
                .get()
                .url(url)
                .addParams("tel", tel)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String NetworkResponseDate = response.body().string();
                        Gson gson =   new Gson();
                        NLogger.e("TAG","=====获取免密码登陆验证码====NetworkResponseDate============"+NetworkResponseDate);
                        final GetVersionBean getVersion = gson.fromJson(NetworkResponseDate,GetVersionBean.class);
                         // TODO 移植
                        MyApplication.getmHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                if(getVersion.errorCode == 200){
                                    mISGetVersionView.showToastInformation("验证码发送成功");
                                }else{
                                   // mISGetVersionView.findshpager();
                                    if(getVersion.errorMessage.equals("手机号已注册！")){
                                        mISGetVersionView.showToastInformation(getVersion.errorMessage);
                                    }else{
                                        mISGetVersionView.showToastInformation(getVersion.errorMessage);
                                    }

                                }
                            }
                        });

                        return null;
                    }
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        MyApplication.getmHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                mISGetVersionView.showToastInformation("验证码发送失败，请重新发送");
                            }
                        });

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }
    //免密码登陆
    private void submitRegisteredOrLogin(String phoneNumber, String trim, final Context mContext) {

        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.PASSWORD_FREE_LOGIN)
                .addParams("tel", phoneNumber)
                .addParams("code",trim)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String NetworkResponseDate = response.body().string();
                        Gson gson = new Gson();
                        NLogger.e("tag","submitRegisteredOrLogin=====免密码登陆====NetworkResponseDate=="+NetworkResponseDate);
                        final PasswordFreeLoginBean passwordFreeLoginBean =  gson.fromJson(NetworkResponseDate, PasswordFreeLoginBean.class);
                        MyApplication.getmHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                if(passwordFreeLoginBean.errorCode == 200) {
                                    mISGetVersionView.toFirstChangeMainPager();
                                    // todo 存储数据 和登陆成功跳转到主页
                                    PasswordFreeLoginBean.DataBean  bean =   passwordFreeLoginBean.data;
                                    if(bean != null) {
                                        mISGetVersionModel.saveDate(bean,mContext);

                                    }
                                    mISGetVersionView.showToastInformation("登陆成功");
                                }else{
                                    mISGetVersionView.showToastInformation(passwordFreeLoginBean.errorMessage);
                                   // mISGetVersionView.findshpager();
                                }
                            }
                        });
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        MyApplication.getmHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                mISGetVersionView.showToastInformation("请查看网络");
                            }
                        });
                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });

    }

}
